package cn.controller;

import cn.basic.BaseController;
import cn.dao.UserDAO;
import cn.factory.DAOFactory;
import cn.model.TUser;
import cn.model.VUserRole;
import cn.util.Expression;
import cn.util.Toolsutil;
import cn.util.Userstatus;
import org.springframework.jmx.export.annotation.ManagedAttribute;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 用户信息数据交互
 * @author WZG
 * @version 2019-10-30
 */
@Controller
@RequestMapping(value="user")
public class UserController extends BaseController {
	/**
	 * 查询用户权限
	 * @param limit  分页参数，一页有多少条，默认10条
	 * @param page   分页参数，从第几页开始显示，默认第1页
	 * @param rolename 模糊查询条件1
	 * @param userid 模糊查询条件2
	 * @param request
	 * @param response
	 * @param model
	 * @throws IOException
	 */
	@RequestMapping(value="getuserlist")//映射路径,拦截post请求
	public void getUserList(
			Integer page,
			Integer limit,//一页多少条
			String userid,//查询条件1
			String rolename,//查询条件2
            String loginstatus,//查询条件3
			HttpServletRequest request,
			HttpServletResponse response,
			Model model) throws IOException{
		//根据传入的参数构建查询条件
		Expression exp = new Expression();
		if (userid != null && !userid.equals(""))
			exp.orLike("userid", userid, String.class);
		if (rolename != null && !rolename.equals("") )
			exp.andEqu("rolename", rolename, String.class);
        if (loginstatus != null && !loginstatus.equals("") && !loginstatus.equals("undefined"))
            exp.andEqu("loginstatus", loginstatus, String.class);
		String wherecondition = exp.toString();
		UserDAO udao = DAOFactory.getUserDAO();
		List<VUserRole> list = udao.getUserList(wherecondition,page, limit);
		int size = udao.getUserAmount(wherecondition);
		if (list!=null) {
			dt.code = dt.FLAG_SUCC;
			dt.msg = "查询成功，共查出" + size + "条记录";
			dt.data = list;
			dt.count = size;
		}else{
			dt.code = dt.FLAG_FAIL;
			dt.msg = "查询失败";
		}
		closeout();
	}

    @RequestMapping(value="getuserpersonal")//映射路径,拦截post请求
    public void getUserPersonal(
            Model model) throws IOException{

        UserDAO udao = DAOFactory.getUserDAO();
        VUserRole user = (VUserRole)session.getAttribute("loginuser");
        String userid =user.getUserid();

        VUserRole list = udao.getVUserRoleById(userid);
        if (list!=null) {
            dt.code = dt.FLAG_SUCC;
            dt.msg = "查询成功" ;
            dt.data = list;
        }else{
            dt.code = dt.FLAG_FAIL;
            dt.msg = "查询失败";
        }
        closeout();
    }
	/**
	 * 实现一个用户的添加
	 * @throws IOException
	 */
	@RequestMapping(value="adduser")
	public void addUser(
			String userid,
			String username,
			String realname,
            Integer roleid,
            String phone,
			String pwd,
			String note,
			HttpServletRequest request,
			HttpServletResponse response,
			Model model) throws IOException{

		UserDAO udao = DAOFactory.getUserDAO();
		TUser user = new TUser();
		user.setUserid(userid);
		user.setUsername(username);
		user.setRealname(realname);
		user.setRoleid(roleid);
        user.setPhone(phone);
        user.setPwd(pwd);
        user.setStatus(Integer.parseInt(Userstatus.ENABLE));
        user.setLastlogindate(Toolsutil.getdatetimes());
        user.setCreatetime(Toolsutil.getdatetimes());
		user.setLoginstatus("未登录");
		user.setNote(note);

		//System.out.println(userid);
		//System.out.println(roleid);

		if (udao.queryUserById(userid)>0) {
			dt.code = dt.FLAG_FAIL;
			dt.msg = "该用户已存在！";
            closeout();
		}else {
			if(udao.addUser(user)>0){
				dt.code = dt.FLAG_SUCC;
				dt.msg = "用户添加成功";
                closeout();
			}else{
				dt.code = dt.FLAG_FAIL;
				dt.msg = "系统原因用户添加失败 ";
			}
		}
		closeout();
	}

	/**
	 * 实现一个用户的删除
	 * @throws IOException
	 */
	@RequestMapping(value="deleteuser")
	public void deleteUser(
	        String userid,
            HttpServletRequest request,
            HttpServletResponse response,
            Model model) throws IOException{
		UserDAO udao = DAOFactory.getUserDAO();
		if (userid !=null && !userid.equals("")){
			udao.deleteUser(userid);
			dt.code = dt.FLAG_SUCC;
			dt.msg = "用户信息删除成功";
		}else {
			dt.code = dt.FLAG_FAIL;
			dt.msg = "用户信息删除失败 ";
		}
		closeout();
	}

	/**
	 * 用户信息修改
	 * @param userid
	 * @param username
	 * @param realname
	 * @param roleid
	 * @param phone
	 * @param note
	 * @param request
	 * @param response
	 * @param model
	 * @throws IOException
	 */
	@RequestMapping(value="modifyuser")
	public void modifyUser(
			String userid,
			String username,
			String realname,
			Integer roleid,
			String phone,
			String note,
			HttpServletRequest request,
			HttpServletResponse response,
			Model model) throws IOException{

		UserDAO udao = DAOFactory.getUserDAO();
		TUser user = udao.getUserById(userid);
		user.setUserid(userid);
		user.setUsername(username);
		user.setRealname(realname);
		user.setRoleid(roleid);
		user.setPwd(user.getPwd());
		user.setPhone(phone);
		user.setStatus(user.getStatus());
		user.setLastlogindate(user.getLastlogindate());
		user.setCreatetime(user.getCreatetime());
		user.setLoginstatus(user.getLoginstatus());
		user.setNote(note);
		if (udao.modifyUser(user)) {
			dt.code = dt.FLAG_SUCC;
			dt.msg = "用户信息修改成功";
		}else {
			dt.code = dt.FLAG_FAIL;
			dt.msg = "用户信息修改失败 ";
		}
		closeout();
	}

	/**
	 * 用户登录
	 * @param userid
	 * @param pwd
	 * @param request
	 * @param response
	 * @param model
	 * @throws IOException
	 */
	@RequestMapping(value="userlogin")
	public void UserLogin(
			String userid,
			String pwd,
			HttpServletRequest request,
			HttpServletResponse response,
			Model model)throws IOException{

		UserDAO udao = DAOFactory.getUserDAO();

		if (userid == null || userid.trim().equals("")) {
			dt.code = dt.FLAG_FAIL;
			dt.msg = "用户名不能为空 ";
		}else if (pwd== null || pwd.trim().equals("")) {
			dt.code = dt.FLAG_FAIL;
			dt.msg = "密码不能为空 ";
		}
		VUserRole pwduser = udao.getVUserRoleById(userid);//查出该用户对应的密码,用于与原密码相比较是否正确

		if (pwduser != null || !pwduser.equals("")) {
			if (!pwd.equals(pwduser.getPwd())) {
				dt.code = dt.FLAG_FAIL;
				dt.msg = "登录失败，密码错误！";
			}else {
				session.setAttribute("loginuser", pwduser);
				List<VUserRole> userlist = udao.userLogin(userid, pwd);//查询出来一个list

				if (userlist != null && userlist.size() > 0) {
					VUserRole user = userlist.get(0);//转换成对象
					if(user != null){
						session.setAttribute("loginuser", pwduser);
						udao.updateInfoByLogin(Toolsutil.getdatetimes(),"登录中",userid);

						dt.code = dt.FLAG_SUCC;
						dt.msg = "登录成功";
					}else{
						dt.code = dt.FLAG_FAIL;
						dt.msg = "登录失败 ";
					}
				}else {
					dt.code = dt.FLAG_FAIL;
					dt.msg = "登录用户不存在！";
				}
			}
			closeout();
		}else {
			dt.code = dt.FLAG_FAIL;
			dt.msg = "登录用户不存在！";
			closeout();
		}
	}

	/**
	 * 修改密码
	 * @param oldpwd
	 * @param newpwd
	 * @param model
	 * @throws IOException
	 */
	@RequestMapping(value="/modifyuserpwd")
	public void modifyUserPwd(
			String oldpwd,
			String newpwd,
			Model model) throws IOException{

		UserDAO udao = DAOFactory.getUserDAO();
		VUserRole user = (VUserRole)session.getAttribute("loginuser");

		if (user!=null) {
			VUserRole pwduser = udao.getVUserRoleById(user.getUserid());//查出该用户对应的密码,用于与原密码相比较是否正确
			String userid =pwduser.getUserid();
			String pwd = pwduser.getPwd();

			//System.out.println(pwduser.getUserid());
			//System.out.println(pwduser.getPwd());
			//System.out.println(newpwd);

			if (!oldpwd.equals(pwd)) {
				dt.code = dt.FLAG_FAIL;
				dt.msg = "请重新输入旧密码！";
			}else {
				if (udao.Upedtpwd(userid,newpwd)) {
					//System.out.println(user.getUserid());
					dt.code = dt.FLAG_SUCC;
					dt.msg = "用户密码修改成功";
					session.removeAttribute("loginuser");
				}else {
					dt.code = dt.FLAG_FAIL;
					dt.msg = "用户密码修改失败";
				}
				closeout();
			}
		}else {
			dt.code = dt.FLAG_FAIL;
			dt.msg = "该用户不存在";
		}
		//回传json字符串
		closeout();
	}

	/**
	 * 退出登录
	 * @throws IOException
	 */
	@RequestMapping(value="outlogin")
	public void Loginout(
			HttpServletRequest request,
			HttpServletResponse response,
			Model model) throws IOException{
		UserDAO udao = DAOFactory.getUserDAO();
		VUserRole vuser = (VUserRole)session.getAttribute("loginuser");
		TUser user = udao.getUserById(vuser.getUserid());

		if (session.getAttribute("loginuser") != null) {
			udao.updateInfoByLogin(user.getLastlogindate(),"未登录",user.getUserid());
			session.removeAttribute("loginuser");
			session.invalidate();//是清除当前session的所有相关信息
			request.getSession().invalidate();
			dt.code = dt.FLAG_SUCC;
			dt.msg = "退出登录成功";

		}else {
			dt.code = dt.FLAG_FAIL;
			dt.msg = "请先登录";
		}
		closeout();
	}
}
